var markdownEditor;

function errorHandler(e) {  
	var msg = '';  

	switch (e.code) {  
	case FileError.QUOTA_EXCEEDED_ERR:  
		msg = 'QUOTA_EXCEEDED_ERR';  
		break;

	case FileError.NOT_FOUND_ERR:  
		msg = 'NOT_FOUND_ERR';
		break;

	case FileError.SECURITY_ERR:  
		msg = 'SECURITY_ERR';  
		break;

	case FileError.INVALID_MODIFICATION_ERR:  
		msg = 'INVALID_MODIFICATION_ERR';  
		break;

	case FileError.INVALID_STATE_ERR:  
		msg = 'INVALID_STATE_ERR';  
		break;

	default:  
		msg = 'Unknown Error';  
		break;  
	};  

	console.log('Error: ' + msg);  
}

function openMarkdonw() {
	console.log('open', "open markdown file");
	chrome.fileSystem.chooseEntry({type: 'openFile'}, 
		function(fileEntry) {
			fileEntry.file(function(file) {  
				var reader = new FileReader();  
				reader.onloadend = function(e) {  
					markdownEditor.setMarkdown(this.result);
				};  
				reader.readAsText(file);  
			}, errorHandler); 
	});
}

function saveMarkdown() {
	chrome.fileSystem.chooseEntry({
		type: 'saveFile',
		suggestedName: 'editor.md'
	}, function(fileEntry) {
		fileEntry.createWriter(function(fileWriter) {
			var blob = new Blob([markdownEditor.getMarkdown()], {type: 'text/plain'});
			fileWriter.write(blob);
		}, errorHandler);
	});
}

function saveHTML() {
	chrome.fileSystem.chooseEntry({
		type: 'saveFile',
		suggestedName: 'editor.html'
	}, function(fileEntry) {
		fileEntry.createWriter(function(fileWriter) {
			var blob = new Blob([markdownEditor.getHTML()], {type: 'text/plain'});
			fileWriter.write(blob);
		}, errorHandler);
	});
}

function convertImageSrc() {
	$(".editormd-preview img").each(function() {
		console.log("img src = ", $(this).attr("src"));
		var xhr = new XMLHttpRequest();
		if($(this).attr("src").indexOf("http://www.emoji-cheat-sheet.com/graphics/emojis/") == 0){
			xhr.open('GET', "emoji-cheat-sheet.com/public/graphics/emojis/"+$(this).attr("src").match(/[^\/]*$/)[0], true);
		} else {
			xhr.open('GET', $(this).attr("src"), true);
		}
		xhr.responseType = 'blob';
		xhr.onload = function(e) {
		 // var img = document.createElement('img');
		   $(this).attr("src", window.URL.createObjectURL(this.response));
		  //document.body.appendChild(img);
		};
		xhr.send();
	});
}

$(function() {
	$.get('editor.md/examples/test.md', function(md){
		markdownEditor = editormd("editormd", {
			width: "100%",
			height: $(document).height(),
			path : 'editor.md/lib/',
			markdown : md,
			codeFold : true,
			saveHTMLToTextarea : true,    // 保存HTML到Textarea
			searchReplace : true,
			//watch : false,                // 关闭实时预览
			htmlDecode : true,            // 开启HTML标签解析，为了安全性，默认不开启    
			//toolbar  : false,             //关闭工具栏
			//previewCodeHighlight : false, // 关闭预览HTML的代码块高亮，默认开启
			emoji : true,
			taskList : true,
			tex : true,                   // 开启科学公式TeX语言支持，默认关闭
			flowChart : true,             // 开启流程图支持，默认关闭
			sequenceDiagram : true,       // 开启时序/序列图支持，默认关闭,
			//dialogLockScreen : false,   // 设置弹出层对话框不锁屏，全局通用，默认为true
			//dialogShowMask : false,     // 设置弹出层对话框显示透明遮罩层，全局通用，默认为true
			//dialogDraggable : false,    // 设置弹出层对话框不可拖动，全局通用，默认为true
			//dialogMaskOpacity : 0.4,    // 设置透明遮罩层的透明度，全局通用，默认值为0.1
			//dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为#fff
			imageUpload : true,
			imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
			imageUploadURL : "./php/upload.php",
			onload : function() {
				console.log('onload', this);
				//this.fullscreen();
				//this.unwatch();
				//this.watch().fullscreen();

				//this.setMarkdown("#PHP");
				//this.width("100%");
				//this.height(480);
				//this.resize("100%", 640);
				$(".editormd-menu").prepend('<li class="divider" unselectable="on">|</li>');
				$(".editormd-menu").prepend('<li><a id="saveas-btn" title="保存HTML" unselectable="on"><i class="fa fa-save" name="saveas" unselectable="on"></i></a></li>')
				$(".editormd-menu").prepend('<li><a id="save-btn" title="保存Markdown" unselectable="on"><i class="fa fa-save" name="save" unselectable="on"></i></a></li>')
				$(".editormd-menu").prepend('<li><a id="open-btn" title="打开Markdown" unselectable="on"><i class="fa fa-file-o" name="open" unselectable="on"></i></a></li>')
				$("#open-btn").bind('click', openMarkdonw);
				$("#save-btn").bind('click', saveMarkdown);
				$("#saveas-btn").bind('click', saveHTML);
				convertImageSrc();
			},
		});
	});
});

